import yaml
from UserInterface.PersistStorage import PersistStorage

class DefaultPersistStorage(PersistStorage):
    def __init__(self, name: str) -> None:
        super().__init__(name)
        self.path = '.'
        self.GenerateFilePath()
        try:
            self.ReadFromStorage()
        except:
            # print(f"read and parse {self.file} fail")
            self.storage = {}

    def Read(self, field: str) -> None:
        if field in self.storage:
            return self.storage[field]

    def Write(self, field: str, value) -> None:
        self.storage[field] = value

    def WriteToStorage(self):
        with open(self.file, 'w', encoding='utf-8') as f:
            yaml.safe_dump(self.storage, f)

    def ReadFromStorage(self):
        with open(self.file, 'r', encoding='utf-8') as f:
            self.storage = yaml.safe_load(f)

    def Save(self) -> None:
        self.WriteToStorage()

    def Load(self) -> None:
        self.ReadFromStorage()

    def SetPath(self, path:str):
        # TODO 判断是否是路径 不存在则创建
        self.path = path
        self.GenerateFilePath()

    def SetName(self, name:str):
        self.name = name
        self.GenerateFilePath()

    def GenerateFilePath(self):
        import os
        fileName = self.name + '.yaml'
        self.file = os.path.join(self.path, fileName)
